<?php

class Mealtime_meals extends CI_Model {
    function __construct(){
        parent::__construct();
    }
    
    function deleteMeals($mealtime_id){
        $this->db->where("mealtime_id", $mealtime_id);
        return $this->db->delete('mealtime_meals');
    }
    
    function addMeal($meal_id, $mealtime_id){
        $this->db->where("meal_id", intval($meal_id));
        $this->db->where('mealtime_id', intval($mealtime_id));
        $results = $this->db->count_all_results('mealtime_meals');
                
        $this->db->flush_cache();
        $data["meal_id"] = intval($meal_id);
        $data["mealtime_id"] = intval($mealtime_id);
        if ($results == 0){
            return $this->db->insert('mealtime_meals', $data);
        }
        else{
            return null;
        }
    }
    
    function updateMeals($meals, $mealtime_id){
        
        //iterate through each meal
        //add if not exists
        if (is_array($meals)){
            foreach($meals as $meal_id){
                $this->db->where("meal_id", intval($meal_id));
                $this->db->where("mealtime_id", intval($mealtime_id));
                $query = $this->db->get('mealtime_meals');
                if ($query->num_rows() == 0){

                    $this->db->flush_cache();

                    $data["meal_id"] = intval($meal_id);
                    $data["mealtime_id"] = intval($mealtime_id);
                    $this->db->insert('mealtime_meals', $data);
                }
            }
        }
        //build delete query
        //delete everything, except where meal id
        $this->db->flush_cache();
        $this->db->where_not_in("meal_id",$meals);
        $this->db->where("mealtime_id",$mealtime_id);
        $this->db->delete("mealtime_meals");
        return true;
    }
    
    function getMealId($mealtime_meals_id){
        $this->db->where("mealtime_meals_id", $mealtime_meals_id);
        $this->db->select("meal_id");
        $query = $this->db->get('mealtime_meals');
        
        if ($query->num_rows() > 0){
            return $query->row()->meal_id;
        }
        else{
            return -1;
        }
    }
    
    function getVoted($user_id, $mealtime_meals_id){
        $this->db->where('user_id', $user_id);
        $this->db->where('mealtime_meals_id', $mealtime_meals_id);
        $query = $this->db->get('user_votes');
        
        return $query->num_rows > 0;
    }
    
    function getOrdered($user_id, $mealtime_meals_id){
        
        $this->db->where('user_id', $user_id);
        $this->db->where('mealtime_meals_id', $mealtime_meals_id);
        $query = $this->db->get('user_orders');
        
        return $query->num_rows > 0;
    }
    
}